package com.starlinkdt.common.utils.Encrypt;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
/**
 * @author zhourenbao
 * @version 1.0
 * @description: TODO
 * @date 2025/6/25 16:04
 */
@Slf4j
public class EncryptUtils {
    // 密钥（需保密，建议配置到 application.yml 中）
    private static final String SECRET_KEY = "rK7sDf9tK2NpQ5vZ7xXwJ2R8gT1uY4wE0qLb3mO6zW2=";
    private static final byte[] SECRET_KEY_BYTES = Base64.getDecoder().decode(SECRET_KEY);

    // 加密方法
    public static String encrypt(String data) {
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            SecretKeySpec keySpec = new SecretKeySpec(SECRET_KEY_BYTES, "AES");
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
            byte[] encrypted = cipher.doFinal(data.getBytes());
            return Base64.getEncoder().encodeToString(encrypted);
        }catch (Exception e) {
            log.error(e.getMessage());
            return data;
        }

    }

    // 解密方法
    public static String decrypt(String encryptedData) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        SecretKeySpec keySpec = new SecretKeySpec(SECRET_KEY_BYTES, "AES");
        cipher.init(Cipher.DECRYPT_MODE, keySpec);
        byte[] decoded = Base64.getDecoder().decode(encryptedData);
        byte[] decrypted = cipher.doFinal(decoded);
        return new String(decrypted);
    }
}